package com.heima.comment.service.impl;
import java.math.BigDecimal;

import com.heima.aliyun.scan.GreenScan;
import com.heima.aliyun.scan.ScanResult;
import com.heima.comment.service.CommentRepayService;
import com.heima.common.exception.CustException;
import com.heima.model.comment.dtos.CommentRepayDTO;
import com.heima.model.comment.dtos.CommentRepayLikeDTO;
import com.heima.model.comment.dtos.CommentRepaySaveDTO;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentRepay;
import com.heima.model.comment.pojos.ApCommentRepayLike;
import com.heima.model.comment.vos.ApCommentRepayVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;
@Service
@Slf4j
public class CommentRepayServiceImpl implements CommentRepayService {
    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    GreenScan greenScan;

    /*
    展示回复
     */
    @Override
    public ResponseResult findByApCommentRepayId(CommentRepayDTO dto) {
        //1. 校验参数
        //   评论id不能为空  size为null 或 0 设置为10  最小日期为空 设置为当前
        if (dto.getMinDate()==null) {
            dto.setMinDate(new Date());
        }
        if (dto.getSize()==null||dto.getSize()<1){
            dto.setSize(10);
        }
        //2. 条件查询评论回复信息
        //   条件:  commentId = 评论id and createdTime 小于 minDate  创建时间 降序  limit size
        Query query = Query.query(Criteria.where("commentId").is(dto.getCommentId()).and("createdTime").lt(dto.getMinDate()))
                .with(Sort.by(Sort.Direction.DESC, "createdTime"))
                .limit(dto.getSize());//评论回复的查询时间
        List<ApCommentRepay> apCommentRepayList = mongoTemplate.find(query, ApCommentRepay.class);//查询到的评论回复
        //3. 检查是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null) {
            //   3.1 如果未登录直接 返回评论回复列表
            return ResponseResult.okResult(apCommentRepayList);
        }
        //   3.2 如果登录，需要判断哪些回复点过赞
        //   思路:
        //        基于当前列表 回复id集合  及  登录人id 查询回复点赞列表
        List<String> repayList = apCommentRepayList.stream().map(ApCommentRepay::getId).collect(Collectors.toList());//获取回复ID
        Query query1 = Query.query(Criteria.where("commentRepayId").in(repayList).and("authorId").is(user.getId()));
        List<ApCommentRepayLike> apCommentRepayLikes = mongoTemplate.find(query1, ApCommentRepayLike.class);
        //        遍历 当前回复列表，将每一个回复信息 封装成 vo
        List<ApCommentRepayVO> commentRepayVOList =new ArrayList<>();
        //所有回复点赞的评论ID LIST
        List<String> collect = apCommentRepayLikes.stream().map(ApCommentRepayLike::getCommentRepayId).distinct().collect(Collectors.toList());
        //遍历评论回复，有点赞的就赋值
        apCommentRepayList.forEach(apCommentRepay -> {
            ApCommentRepayVO apCommentRepayVO = new ApCommentRepayVO();
            BeanUtils.copyProperties(apCommentRepay,apCommentRepayVO);
            if(collect.contains(apCommentRepay.getId())){
                apCommentRepayVO.setOperation((short)0);

            }
            commentRepayVOList.add(apCommentRepayVO);
        });
        //        判断当前回复id 在点赞信息中是否存在，如果存在 operation设置为0 不存在不做处理
        return ResponseResult.okResult(commentRepayVOList);
    }

    /*
    保存回复
     */
    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDTO dto) {
        //1. 参数校验:
        //   是否登录  评论id是否为空  内容是否为空  内容是否大于140个字符
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //   回复内容安全校验
        //        简单: 不校验      普通: 阿里云内容检查，有问题抛异常     困难：阿里云内容检查，有问题替换为**
        String content = dto.getContent();
        try {
            ScanResult scanResult = greenScan.greenTextScan(content);
            String filteredContent = scanResult.getFilteredContent();
            if(filteredContent!=null){
                dto.setContent(filteredContent);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //2. 根据评论id查询评论信息  检查是否存在
        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        if(apComment==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //3. 保存评论回复信息
        ApCommentRepay repay = new ApCommentRepay();
        repay.setAuthorId(user.getId());
        repay.setAuthorName(user.getName());
        repay.setCommentId(dto.getCommentId());
        repay.setContent(dto.getContent());
        repay.setLikes(0);
        repay.setCreatedTime(new Date());
        repay.setUpdatedTime(new Date());
        mongoTemplate.save(repay);

        //4. 修改评论信息中回复数量 + 1
        Integer reply = apComment.getReply();
        reply +=1;
        apComment.setReply(reply);
        return ResponseResult.okResult();
    }

    /*
    保存回复点赞
     */
    @Override
    public ResponseResult saveCommentRepayLike(CommentRepayLikeDTO dto) {
        //1. 校验参数
        //       回复id不能为空   operation 必须 0 或 1
        //       校验登录  (必须登录)
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //       校验回复信息是否存在
        ApCommentRepay apCommentRepay = mongoTemplate.findById(dto.getCommentRepayId(), ApCommentRepay.class);//查询回复的评论
        if (apCommentRepay==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        Integer likes = apCommentRepay.getLikes();
        Map result =new HashMap<>();
        //1. 如果是点赞  判断是否点过赞
        Query query = Query.query(Criteria.where("authorId").is(user.getId()).and("commentRepayId").is(dto.getCommentRepayId()));
        ApCommentRepayLike apCommentRepayLike = mongoTemplate.findOne(query, ApCommentRepayLike.class);
        Short operation = dto.getOperation();
        //      点过赞提示请勿重复点赞
        if(operation==0){
            if (apCommentRepayLike!=null){
                CustException.cust(AppHttpCodeEnum.DATA_EXIST,"不可重复点赞");
            }else {        //      未点过赞， 保存点赞信息
                ApCommentRepayLike repayLike = new ApCommentRepayLike();
                repayLike.setAuthorId(user.getId());
                repayLike.setCommentRepayId(dto.getCommentRepayId());
                repayLike.setOperation((short)0);
                mongoTemplate.save(repayLike);
            }
            likes+=1;//       并将回复信息的点赞数量字段+1
        }else {
            //1. 如果是取消赞
            //      删除点赞
            mongoTemplate.remove(apCommentRepayLike);
            //     并将回复信息的点赞数量字段
            likes-=1;
            if(likes<0){
                CustException.cust(AppHttpCodeEnum.SERVER_ERROR);
            }
        }
        apCommentRepay.setLikes(likes);
        mongoTemplate.save(apCommentRepay);
        //1. 返回当前回复的最新点赞数量      数据的key:  likes
        result.put("likes",likes);
        return ResponseResult.okResult(result);
    }
}
